<template>
  <view style="height: 100vh">
    <web-view ref="webview" :src="src" @message="handleMessage" />
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import store from '@/store'

const src = ref('')

onLoad((e) => {
  const NODE_ENV = process.env.NODE_ENV
  const url =
    NODE_ENV === 'development'
      ? 'https://activate-qa1.meilianshuke.com/#/'
      : 'https://activate.meilianshuke.com/#/'

  // src.value = `${url}?token=store.state.token&empi=${store.state.userInfo.patientInfo.empi}`
  src.value = `${url}?token=${store.state.token}&empi=${store.state.userInfo.patientInfo.empi}`

  if (e) {
    if (e.imgUrl) {
      console.log('e.imgUrl', e.imgUrl)

      uni.getSetting({
        success: (res) => {
          if (res.authSetting['scope.writePhotosAlbum']) {
            // 已授权
            saveImg(e.imgUrl)
          } else {
            uni.authorize({
              scope: 'scope.writePhotosAlbum',
              success: () => {
                // console.log('同意')
                // 用户已经同意授权
                saveImg(e.imgUrl)
              },
              fail: () => {
                uni.showToast({
                  icon: 'none',
                  title: '请前往设置页开启保存到相册权限',
                  success: function (modalRes) {
                    if (modalRes.confirm) {
                      uni.openSetting()
                    }
                  }
                })
              }
            })
          }
        }
      })
    }
  }
})

const saveImg = (url: any) => {
  uni.downloadFile({
    url: url,
    success: (res) => {
      if (res.tempFilePath) {
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function () {
            uni.showToast({
              icon: 'none',
              title: '保存成功并保存到相册',
              showCancel: false
            })
          },
          fail: function (err) {
            console.log(err)
            uni.showToast({
              icon: 'error',
              title: '保存失败',
              showCancel: false
            })
          }
        })
      } else {
        console.log('下载失败')
      }
    }
  })
}

const load = () => {
  console.log('页面加载成功')
}
const postMessage = (e) => {
  console.log('postMessage', e)
}

const handleMessage = (e) => {
  // console.log('message:wx', e)
  // debugger
  const lastMsg = e.detail.data.at(-1)
  if (lastMsg && typeof lastMsg === 'object') {
    console.log('lastMsg', lastMsg.url)
    console.log(lastMsg.url)
  }
}

const catchError = (err) => {
  console.log('页面加载失败', err)
}
</script>

<style lang="scss" scoped></style>
